package space.panker916.controller.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import space.panker916.annotation.LoginRequired;
import space.panker916.utils.HostHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @program: fake-nowcoder
 * @description:
 * @author: PanKer
 * @create: 2022-04-11 12:57
 */

@Deprecated
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // handler = space.panker916.controller.UserController#getSettingPage()
        // 包名 + 方法名 （调用方法的信息 ？）
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            LoginRequired loginRequired = handlerMethod.getMethodAnnotation(LoginRequired.class);
            if (loginRequired != null && hostHolder.getUser() == null) {

                // 判断是 普通请求（直接重定向） 还是 异步请求（向后台返回信息，在 Ajax 处重定向）
                String xReq = request.getHeader("x-requested-with");
                if (StringUtils.isNotBlank(xReq) && "XMLHttpRequest".equalsIgnoreCase(xReq)) {
                    // 是ajax异步请求
                    PrintWriter out = response.getWriter();//如果是ajax请求，返回一个标识，告诉ajax请求无效，需要重新登录
                    out.print("login");
                } else response.sendRedirect(request.getContextPath() + "/login");

                return false;
            }
        }
        return true;
    }
}
